package cn.net.shuxing.yifu.common.back.controller;

import cn.net.shuxing.yifu.common.bean.*;
import cn.net.shuxing.yifu.common.constant.DealScene;
import cn.net.shuxing.yifu.common.constant.DealType;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.service.*;
import cn.net.shuxing.yifu.common.util.SpringUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import cn.net.shuxing.yifu.common.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 订单管理Controller
 */
@RestController
@RequestMapping("/back/order")
public class OrderManageController {

    @Autowired
    private UserRealInfoService userRealInfoService;

    @Autowired
    private HangBuyService hangBuyService;

    @Autowired
    private HangSaleService hangSaleService;

    @Autowired
    private DealCommonService dealCommonService;

    @Autowired
    private DealHistoryService dealHistoryService;

    @Autowired
    private UserCommonService userCommonService;

    @Autowired
    private CoinTypeService coinTypeService;

    @Autowired
    private HangBuyDetailListService hangBuyDetailListService;

    @Autowired
    private HangSaleDetailListService hangSaleDetailListService;

    @Autowired
    private UserInfoBindService userInfoBindService;

    /**
     * 查询以下现有的参数
     *
     * @param phoneNum
     * @param realName
     * @param lowAliveCount
     * @param highAliveCount
     * @param lowDealtCount
     * @param highDealtCount
     * @param lowDate1
     * @param highDate1
     * @return
     */
    @RequestMapping(value = "/hangBuy/search")
    public BaseDto searchHangBuy(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                                 @RequestParam(defaultValue = "15", value = "pageSize") int pageSize,
                                 String phoneNum,
                                 String realName,
                                 BigDecimal lowAliveCount,
                                 BigDecimal highAliveCount,
                                 BigDecimal lowDealtCount,
                                 BigDecimal highDealtCount,
                                 String lowDate1,
                                 String highDate1) {
        LocalDate lowDate = null;
        LocalDate highDate = null;
        if (StringUtils.hasText(lowDate1)) {
            lowDate = LocalDate.parse(lowDate1);
        }
        if (StringUtils.hasText(highDate1)) {
            highDate = LocalDate.parse(highDate1);
        }
        List<HangBuy> hangBuys = hangBuyService.searchHangBuy(phoneNum, realName, lowAliveCount, highAliveCount, lowDealtCount, highDealtCount, lowDate, highDate);
        ArrayList<HangBuyList> list = new ArrayList<>();
        for (HangBuy hangBuy : hangBuys) {
            HangBuyList hangBuyList = new HangBuyList();
            Integer userId = hangBuy.getUserId();
            UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(userId);
            //挂买单号
            Integer hangBuyId = hangBuy.getId();
            hangBuyList.setHangBuyId(hangBuyId);
            //挂买人
            String hangBuyUser = userCompletedInfo.getUserRealInfo().getRealName();
            hangBuyList.setHangBuyUser(hangBuyUser);
            //手机号
            String phoneNum1 = userCompletedInfo.getUserInfoBind().getPhoneNum();
            hangBuyList.setPhoneNum(phoneNum1);
            //币种
            String coinType = coinTypeService.getByPrimaryKey(hangBuy.getCoinTypeId()).getName();
            hangBuyList.setCoinType(coinType);
            //挂买数量
            BigDecimal hangBuyNum = hangBuy.getAliveCoinCount();
            hangBuyList.setHangBuyNum(hangBuyNum);
            //挂买单价
            BigDecimal hangBuyPrice = hangBuy.getSinglePrice();
            hangBuyList.setHangBuyPrice(hangBuyPrice);
            //已交易数量
            BigDecimal surplusCoinCount = hangBuy.getSurplusCoinCount();//余量
            BigDecimal hangBuyDealNum = hangBuyNum.subtract(surplusCoinCount);
            hangBuyList.setHangBuyDealNum(hangBuyDealNum);
            //挂买单状态
            Integer stateNum = hangBuy.getState();
            hangBuyList.setStateNum(stateNum);
            String hangBuyState = "";
            if (stateNum == 0) {
                hangBuyState = "已完成";
            } else if (stateNum == 1) {
                hangBuyState = "交易中";
            } else if (stateNum == 2) {
                hangBuyState = "异常";
            } else {
                hangBuyState = "已撤单";
            }
            hangBuyList.setHangBuyState(hangBuyState);
            //发布时间
            LocalDateTime publistTime = hangBuy.getCreateTime();
            hangBuyList.setPublistTime(publistTime);
            list.add(hangBuyList);
        }
        BaseDto baseDto = new BaseDto();
        Page<HangBuy> page = PageHelper.startPage(pageNum, pageSize);
        PageInfo<HangBuyList> pageInfo = new PageInfo<>(list);
        //pageInfo.setTotal(page.getTotal());
        baseDto.setData(pageInfo);
        return baseDto;
    }

    /**
     * 取消发布的订单
     *
     * @param hangBuyId
     * @return
     */
    @RequestMapping(value = "/hangBuy/cancel")
    public BaseDto cancelHangBuy(Integer hangBuyId) {
        return hangBuyService.cancel(hangBuyId);
    }

    @RequestMapping(value = "/hangSale/search")
    public BaseDto searchHangSale(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                                  @RequestParam(defaultValue = "15", value = "pageSize") int pageSize,
                                  String phoneNum,
                                  String realName,
                                  BigDecimal lowAliveCount,
                                  BigDecimal highAliveCount,
                                  BigDecimal lowDealtCount,
                                  BigDecimal highDealtCount,
                                  String lowDate1,
                                  String highDate1) {
        LocalDate lowDate = null;
        LocalDate highDate = null;
        if (StringUtils.hasText(lowDate1)) {
            lowDate = LocalDate.parse(lowDate1);
        }
        if (StringUtils.hasText(highDate1)) {
            highDate = LocalDate.parse(highDate1);
        }
        //Page page = PageHelper.startPage(pageNum,pageSize);
        List<HangSale> hangSales = hangSaleService.searchHangSale(phoneNum, realName, lowAliveCount, highAliveCount, lowDealtCount, highDealtCount, lowDate, highDate);
        ArrayList<HangSaleList> list = new ArrayList<>();
        for (HangSale hangSale : hangSales) {
            HangSaleList hangSaleList = new HangSaleList();
            Integer userId = hangSale.getUserId();
            UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(userId);
            //挂买单号
            Integer hangSaleId = hangSale.getId();
            hangSaleList.setHangSaleId(hangSaleId);
            //挂买人
            String hangSaleUser = userCompletedInfo.getUserRealInfo().getRealName();
            hangSaleList.setHangSaleUser(hangSaleUser);
            //手机号
            String phoneNum1 = userCompletedInfo.getUserInfoBind().getPhoneNum();
            hangSaleList.setPhoneNum(phoneNum1);
            //币种
            String coinType = coinTypeService.getByPrimaryKey(hangSale.getCoinTypeId()).getName();
            hangSaleList.setCoinType(coinType);
            //挂买数量
            BigDecimal hangSaleNum = hangSale.getAliveCoinCount();
            hangSaleList.setHangSaleNum(hangSaleNum);
            //挂买单价
            BigDecimal hangSalePrice = hangSale.getSinglePrice();
            hangSaleList.setHangSalePrice(hangSalePrice);
            //已交易数量
            BigDecimal surplusCoinCount = hangSale.getSurplusCoinCount();//余量
            BigDecimal hangSaleDealNum = hangSaleNum.subtract(surplusCoinCount);
            hangSaleList.setHangSaleDealNum(hangSaleDealNum);
            //挂买单状态
            Integer stateNum = hangSale.getState();
            hangSaleList.setStateNum(stateNum);
            String hangSaleState = "";
//            状态,0表示已完成,1表示交易中,2表示失败,3撤单
            if (stateNum == 0) {
                hangSaleState = "已完成";
            } else if (stateNum == 1) {
                hangSaleState = "交易中";
            } else if (stateNum == 2) {
                hangSaleState = "失败";
            } else if (stateNum == 3) {
                hangSaleState = "撤单";
            }
            hangSaleList.setHangSaleState(hangSaleState);
            //发布时间
            LocalDateTime publistTime = hangSale.getCreateTime();
            hangSaleList.setPublistTime(publistTime);
            list.add(hangSaleList);
        }
        BaseDto baseDto = new BaseDto();
        PageInfo<HangSaleList> pageInfo = new PageInfo<>(list);
        //pageInfo.setTotal(page.getTotal());
        baseDto.setData(pageInfo);
        return baseDto;
    }

    @RequestMapping(value = "/hangSale/cancel")
    public BaseDto cancelHangSale(Integer hangSaleId) {
        return hangSaleService.cancel(hangSaleId);
    }

    @RequestMapping("/hangBuy/detail")
    public BaseDto hangBuyDetail(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                                 @RequestParam(defaultValue = "15", value = "pageSize") int pageSize,
                                 Integer hangBuyId) {
        BaseDto baseDto = new BaseDto();
        //Page page = PageHelper.startPage(pageNum,pageSize);
        ArrayList<HangBuyDetailList> list = new ArrayList<>();
        List<DealHistory> dealHistories = dealHistoryService.getsByHangBuyId(hangBuyId, DealScene.HANG_BUY);
        for (DealHistory dealHistory : dealHistories) {
            HangBuyDetailList hangBuyDetailList = new HangBuyDetailList();
            //挂卖单号
            hangBuyDetailList.setHangBuyId(hangBuyId);
            //卖方姓名
            Integer saleUserId = dealHistory.getBuyUserId();
            UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(saleUserId);
            hangBuyDetailList.setHangBuyUser(userCompletedInfo.getUserRealInfo().getRealName());
            //卖方手机号
            hangBuyDetailList.setPhoneNum(userCompletedInfo.getUserInfoBind().getPhoneNum());
            //交易数量
            hangBuyDetailList.setHangBuyDealNum(dealHistory.getDealAliveCoinCount());
            //交易时间
            hangBuyDetailList.setDealTime(dealHistory.getCreateTime());
            list.add(hangBuyDetailList);
        }
        PageInfo<HangBuyDetailList> pageInfo = new PageInfo<>(list);
        //pageInfo.setTotal(page.getTotal());
        baseDto.setData(pageInfo);
        return baseDto;
    }

    //    交易记录，包括挂卖单号、卖方姓名、卖方手机号、交易数量、交易时间
    @RequestMapping("/hangSale/detail")
    public BaseDto hangSaleDetail(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                                  @RequestParam(defaultValue = "15", value = "pageSize") int pageSize,
                                  Integer hangSaleId) {
        BaseDto baseDto = new BaseDto();
        ArrayList<HangSaleDetailList> list = new ArrayList<>();
        //Page page = PageHelper.startPage(pageNum,pageSize);
        List<DealHistory> dealHistories = dealHistoryService.getsByDealIdAndDealScene(hangSaleId, DealScene.HANG_SALE);
        for (DealHistory dealHistory : dealHistories) {
            HangSaleDetailList hangSaleDetailList = new HangSaleDetailList();
            //挂卖单号
            hangSaleDetailList.setHangSaleId(hangSaleId);
            //卖方姓名
            Integer saleUserId = dealHistory.getSaleUserId();
            UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(saleUserId);
            hangSaleDetailList.setHangSaleUser(userCompletedInfo.getUserRealInfo().getRealName());
            //卖方手机号
            hangSaleDetailList.setPhoneNum(userCompletedInfo.getUserInfoBind().getPhoneNum());
            //交易数量
            hangSaleDetailList.setHangSaleDealNum(dealHistory.getDealAliveCoinCount());
            //交易时间
            hangSaleDetailList.setDealTime(dealHistory.getCreateTime());
            list.add(hangSaleDetailList);
        }
        PageInfo<HangSaleDetailList> pageInfo = new PageInfo<>(list);
        //pageInfo.setTotal(page.getTotal());
        baseDto.setData(pageInfo);
        return baseDto;
    }

    // 编号、挂买单号、挂买人、手机号、币种、挂买数量、挂买单价、已交易数量、挂买单状态、发布时间、操作
//    @RequestMapping("/hangBuy/list")
//    public BaseDto hangBuyList(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
//                               @RequestParam(defaultValue = "15", value = "pageSize") int pageSize) {
//        BaseDto baseDto = new BaseDto();
//        List<HangBuy> all = hangBuyService.getAll();
//        ArrayList<HangBuyList> list = new ArrayList<>();
//        for (HangBuy hangBuy : all) {
//            HangBuyList hangBuyList = new HangBuyList();
//            Integer userId = hangBuy.getUserId();
//            UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(userId);
//            //挂买单号
//            Integer hangBuyId = hangBuy.getId();
//            hangBuyList.setHangBuyId(hangBuyId);
//            //挂买人
//            String hangBuyUser = userCompletedInfo.getUserRealInfo().getRealName();
//            hangBuyList.setHangBuyUser(hangBuyUser);
//            //手机号
//            String phoneNum = userCompletedInfo.getUserInfoBind().getPhoneNum();
//            hangBuyList.setPhoneNum(phoneNum);
//            //币种
//            String coinType = coinTypeService.getByPrimaryKey(hangBuy.getCoinTypeId()).getName();
//            hangBuyList.setCoinType(coinType);
//            //挂买数量
//            BigDecimal hangBuyNum = hangBuy.getAliveCoinCount();
//            hangBuyList.setHangBuyNum(hangBuyNum);
//            //挂买单价
//            BigDecimal hangBuyPrice = hangBuy.getSinglePrice();
//            hangBuyList.setHangBuyPrice(hangBuyPrice);
//            //已交易数量
//            BigDecimal surplusCoinCount = hangBuy.getSurplusCoinCount();//余量
//            BigDecimal hangBuyDealNum = hangBuyNum.subtract(surplusCoinCount);
//            hangBuyList.setHangBuyDealNum(hangBuyDealNum);
//            //挂买单状态
//            Integer stateNum = hangBuy.getState();
//            String hangBuyState = "";
//            if (stateNum == 0) {
//                hangBuyState = "已完成";
//            } else if (stateNum == 1) {
//                hangBuyState = "撤单";
//            } else if (stateNum == 2) {
//                hangBuyState = "交易中";
//            } else {
//                hangBuyState = "订单异常";
//            }
//            hangBuyList.setHangBuyState(hangBuyState);
//            //发布时间
//            LocalDateTime publistTime = hangBuy.getCreateTime();
//            hangBuyList.setPublistTime(publistTime);
//            list.add(hangBuyList);
//        }
//        //Page page = PageHelper.startPage(pageNum,pageSize)
//        baseDto.setData(new PageInfo<HangBuyList>(list));
//        return baseDto;
//    }

    // 编号、挂买单号、挂买人、手机号、币种、挂买数量、挂买单价、已交易数量、挂买单状态、发布时间、操作
//    @RequestMapping("/hangSale/list")
//    public BaseDto hangSaleList(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
//                                @RequestParam(defaultValue = "15", value = "pageSize") int pageSize) {
//        BaseDto baseDto = new BaseDto();
//        List<HangSale> all = hangSaleService.getAll();
//
//        ArrayList<HangSaleList> list = new ArrayList<>();
//        for (HangSale hangSale : all) {
//            HangSaleList hangSaleList = new HangSaleList();
//            Integer userId = hangSale.getUserId();
//            UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(userId);
//            //挂买单号
//            Integer hangSaleId = hangSale.getId();
//            hangSaleList.setHangSaleId(hangSaleId);
//            //挂买人
//            String hangSaleUser = userCompletedInfo.getUserRealInfo().getRealName();
//            hangSaleList.setHangSaleUser(hangSaleUser);
//            //手机号
//            String phoneNum = userCompletedInfo.getUserInfoBind().getPhoneNum();
//            hangSaleList.setPhoneNum(phoneNum);
//            //币种
//            String coinType = coinTypeService.getByPrimaryKey(hangSale.getCoinTypeId()).getName();
//            hangSaleList.setCoinType(coinType);
//            //挂买数量
//            BigDecimal hangSaleNum = hangSale.getAliveCoinCount();
//            hangSaleList.setHangSaleNum(hangSaleNum);
//            //挂买单价
//            BigDecimal hangSalePrice = hangSale.getSinglePrice();
//            hangSaleList.setHangSalePrice(hangSalePrice);
//            //已交易数量
//            BigDecimal surplusCoinCount = hangSale.getSurplusCoinCount();//余量
//            BigDecimal hangSaleDealNum = hangSaleNum.subtract(surplusCoinCount);
//            hangSaleList.setHangSaleDealNum(hangSaleDealNum);
//            //挂买单状态
//            Integer stateNum = hangSale.getState();
//            String hangSaleState = "";
//            if (stateNum == 0) {
//                hangSaleState = "已完成";
//            } else if (stateNum == 1) {
//                hangSaleState = "撤单";
//            } else if (stateNum == 2) {
//                hangSaleState = "交易中";
//            } else {
//                hangSaleState = "订单异常";
//            }
//            hangSaleList.setHangSaleState(hangSaleState);
//            //发布时间
//            LocalDateTime publistTime = hangSale.getCreateTime();
//            hangSaleList.setPublistTime(publistTime);
//            list.add(hangSaleList);
//        }
//        //Page page = PageHelper.startPage(pageNum,pageSize)
//        baseDto.setData(new PageInfo<HangSaleList>(list));
//        return baseDto;
//    }

    /**
     * 根据hangBuyId 更改删除状态
     *
     * @param response
     * @param hangBuyId
     * @throws IOException
     */
    @RequestMapping("/hangBuy/del")
    public BaseDto hangBuyDel(HttpServletResponse response, @Param("hangBuyId") int hangBuyId) throws IOException {
        return hangBuyService.cancel(hangBuyId);
    }


    /**
     * 根据hangSaleId 更改删除状态
     *
     * @param response
     * @param hangSaleId
     * @throws IOException
     */
    @RequestMapping("/hangSale/del")
    public BaseDto hangSaleDel(HttpServletResponse response, @Param("hangSaleId") int hangSaleId) throws IOException {
        return hangSaleService.cancel(hangSaleId);
    }

    @RequestMapping("/hangBuy/list")
    public BaseDto getHangBuyList(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                                  @RequestParam(defaultValue = "15", value = "pageSize") int pageSize) {
        BaseDto baseDto = new BaseDto();
        //Page page = PageHelper.startPage(pageNum,pageSize);
        PageInfo<HangBuy> pageInfo = new PageInfo<>(hangBuyService.getAll());
        //pageInfo.setTotal(page.getTotal());
        baseDto.setData(pageInfo);
        return baseDto;
    }

    @RequestMapping("/hangSale/list")
    public BaseDto getHangSaleList(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                                   @RequestParam(defaultValue = "15", value = "pageSize") int pageSize) {
        BaseDto baseDto = new BaseDto();
        //Page page = PageHelper.startPage(pageNum,pageSize);
        PageInfo<HangSale> pageInfo = new PageInfo<>(hangSaleService.getAll());
        //pageInfo.setTotal(page.getTotal());
        baseDto.setData(pageInfo);
        return baseDto;
    }

}
